package com.ocom.webapi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.constant.WebApiServiceUrl;
import com.ocom.common.dto.UnitsPageOnShowDto;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.CompanyListInfoVo;
import com.ocom.security.authentication.YoCiUser;
import com.ocom.security.utils.SecurityUtils;
import com.ocom.webapi.feign.CompanyClientService;
import com.ocom.webapi.feign.HumanClientService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@PreAuthorize("@pms.hasRole('ROLE_WEB')" )
public class PermissionsController {

    @Autowired
    private HumanClientService humanClientService;

    @Autowired
    private CompanyClientService companyClientService;

    @PostMapping(WebApiServiceUrl.URL_PermissionSysRoleList)
    public Result permissionSysRoleList(){
        return humanClientService.getSysRoleList();
    }

    @PostMapping(WebApiServiceUrl.URL_PageEnumOnShow)
    public Result pageEnumOnShow(@RequestBody JSONObject jsonObject){
        return humanClientService.getPageEnumByType(jsonObject.getString("type"));
    }

    @PostMapping(WebApiServiceUrl.URL_PermissionWebPageList)
    public Result PermissionWebPageList(@RequestBody JSONObject rsjsonObject){
        Integer parentId = rsjsonObject.getIntValue("parentId");
        if (rsjsonObject.getInteger("retPermission")==0){
            return humanClientService.webPageList(parentId);
        }else {
            Result result=humanClientService.getRolePagePermission(-2,0L,0);
            Result results=humanClientService.webPageList(parentId);
            Map<String,Object> maps= JSON.parseObject(JSON.toJSONString(results.getData()));
            List<JSONObject> lists=JSON.parseArray(JSON.toJSONString(maps.get("pageList")),JSONObject.class);
            List<JSONObject> re=new ArrayList<>();
            for (JSONObject res : lists) {
                Map<String,Object> map= JSON.parseObject(JSON.toJSONString(result.getData()));
                List<JSONObject> list=JSON.parseArray(JSON.toJSONString(map.get("permissionList")),JSONObject.class);
                for (JSONObject jsonObject : list) {
                    if (res.getInteger("pageId").compareTo(jsonObject.getInteger("pageId"))==0){
                        if (jsonObject.getByte("permission")==1){
                            if (res.getString("permission1")==null){
                                res.put("permission1",jsonObject.getInteger("role"));
                            }else {
                                res.put("permission1",res.getString("permission1")+","+jsonObject.getInteger("role"));
                            }
                        }else if (jsonObject.getByte("permission")==2){
                            if (res.getString("permission2")==null){
                                res.put("permission2",jsonObject.getInteger("role"));
                            }else {
                                res.put("permission2",res.getString("permission2")+","+jsonObject.getInteger("role"));
                            }
                        }
                    }
                }
                re.add(res);
            }
            Map<String,Object> map=new HashMap<>();
            map.put("permissionList",re);
            return ResultUtil.success(map);
        }
    }

    /**
     *@Description:添加WEB页面
     * @author lu 
     * @param jsonObject
     * @return com.ocom.common.resp.Result
     * @date 2022/11/3 13:17       
     */
    @PostMapping(WebApiServiceUrl.URL_PermissionAddWebPage)
    public Result permissionAddWebPage(@RequestBody JSONObject jsonObject){
        Result result=humanClientService.addWebPage(jsonObject.getString("pageCode"),jsonObject.getString("pageName"),jsonObject.getString("description"),jsonObject.getString("pageAppCode"),jsonObject.getIntValue("parentId"));
        if (result.getCode()==200){
            JSONObject object=JSON.parseObject(JSON.toJSONString(result.getData()),JSONObject.class);
            jsonObject.put("pageId",object.getInteger("pageId"));
            return humanClientService.setPagePermission(jsonObject);
        }else {
            return result;
        }
    }

    @PostMapping(WebApiServiceUrl.URL_PermissionModifyWebPage)
    public Result permissionModifyWebPage(@RequestBody JSONObject jsonObject){
        Result result=humanClientService.modifyWebPage(jsonObject.getInteger("pageId"),jsonObject.getString("pageName"),jsonObject.getString("description"),jsonObject.getString("pageCode"),jsonObject.getString("pageAppCode"),jsonObject.getIntValue("parentId"));
        if (result.getCode()==200){
            jsonObject.put("buttonId",0);
            return humanClientService.setPagePermission(jsonObject);
        }else {
            return result;
        }
    }

    /**
     *@Description:2.12.5获取页面按钮列表（Permission/webButtonList）
     * @author lu 
     * @param rsjsonObject
     * @return com.ocom.common.resp.Result
     * @date 2022/11/4 13:19       
     */
    @PostMapping(WebApiServiceUrl.URL_PermissionWebButtonList)
    public Result permissionWebButtonList(@RequestBody JSONObject rsjsonObject){
        Result results=humanClientService.getWebButtonList(rsjsonObject.getInteger("pageId"));
        if (rsjsonObject.getInteger("retPermission")==0){
            return results;
        }else {
            Result result=humanClientService.getRoleButtonPermission(-2,0,rsjsonObject.getInteger("pageId"));
            Map<String,Object> maps= JSON.parseObject(JSON.toJSONString(results.getData()));
            List<JSONObject> lists=JSON.parseArray(JSON.toJSONString(maps.get("buttonList")),JSONObject.class);
            List<JSONObject> re=new ArrayList<>();
            for (JSONObject res : lists) {
                Map<String,Object> map= JSON.parseObject(JSON.toJSONString(result.getData()));
                List<JSONObject> list=JSON.parseArray(JSON.toJSONString(map.get("permissionList")),JSONObject.class);
                for (JSONObject jsonObject : list) {
                    if (jsonObject.getByte("permission")==1){
                        if (res.getString("permission1")==null){
                            res.put("permission1",jsonObject.getInteger("role"));
                        }else {
                            res.put("permission1",res.getString("permission1")+","+jsonObject.getInteger("role"));
                        }
                    }
                }
                re.add(res);
            }
            Map<String,Object> map=new HashMap<>();
            map.put("permissionList",re);
            return ResultUtil.success(map);
        }
    }

    /**
     *@Description:删除页面按钮（Permission/removeWebButton）
     * @author lu 
     * @param rsjsonObject
     * @return com.ocom.common.resp.Result
     * @date 2022/11/4 14:47       
     */
    @PostMapping(WebApiServiceUrl.URL_removeWebButton)
    public Result removeWebButton(@RequestBody JSONObject rsjsonObject){
        return humanClientService.deleteWebButton(rsjsonObject.getInteger("pageId"),rsjsonObject.getInteger("buttonId"));
    }

    /**
     *@Description:添加WEB页面按钮
     * @author lu 
     * @param jsonObject
     * @return com.ocom.common.resp.Result
     * @date 2022/11/4 14:58       
     */
    @PostMapping(WebApiServiceUrl.URL_PermissionaddWebButton)
    public Result permissionaddWebButton(@RequestBody JSONObject jsonObject){
        Result result=humanClientService.addWebButton(jsonObject.getInteger("pageId"),jsonObject.getString("pageCode"),jsonObject.getString("pageName"),jsonObject.getString("description"));
        if (result.getCode()==200){
            JSONObject object=JSON.parseObject(JSON.toJSONString(result.getData()),JSONObject.class);
            jsonObject.put("buttonId",object.getInteger("buttonId"));
            return humanClientService.setPagePermission(jsonObject);
        }else {
            return result;
        }
    }

    /**
     *@Description:修改WEB页面按钮（Permission/modifyWebButton）
     * @author lu 
     * @param jsonObject
     * @return com.ocom.common.resp.Result
     * @date 2022/11/4 15:01       
     */
    @PostMapping(WebApiServiceUrl.URL_PermissionmodifyWebButton)
    public Result permissionmodifyWebButton(@RequestBody JSONObject jsonObject){
        Result result=humanClientService.modifyWebButton(jsonObject.getInteger("pageId"),jsonObject.getInteger("buttonId"),jsonObject.getString("buttonName"),jsonObject.getString("description"));
        if (result.getCode()==200){
            return humanClientService.setPagePermission(jsonObject);
        }else {
            return result;
        }
    }

    /**
     *@Description:获取消费版本列表
     * @author lu
     * @return com.ocom.common.resp.Result
     * @date 2022/11/7 9:46       
     */
    @PostMapping(WebApiServiceUrl.URL_PermissionxfVerList)
    public Result permissionxfVerList(){
        return humanClientService.getXfVerList();
    }

    /**
     *@Description:获取门禁版本列表
     * @author lu
     * @return com.ocom.common.resp.Result
     * @date 2022/11/7 9:48       
     */
    @PostMapping(WebApiServiceUrl.URL_PermissionmjVerList)
    public Result permissionmjVerList(){
        return humanClientService.getMjVerList();
    }


    /**
     *@Description:获取SaaS菜单列表
     * @author lu 
     * @param jsonObject
     * @return com.ocom.common.resp.Result
     * @date 2022/11/8 13:24       
     */
    @PostMapping(WebApiServiceUrl.URL_PermissionsaasMenuList)
    public Result permissionsaasMenuList(@RequestBody JSONObject jsonObject){
        return humanClientService.getSaasMenuList(jsonObject.getInteger("saasNo"));
    }

    @PostMapping(WebApiServiceUrl.URL_PermissionremoveSaasMenu)
    public Result permissionremoveSaasMenu(@RequestBody JSONObject jsonObject){
        return humanClientService.removeSaasMenu(jsonObject.getInteger("saasNo"),jsonObject.getInteger("menuId"));
    }


    /**
     *@Description:上移SaaS菜单
     * @author lu 
     * @param jsonObject 
     * @return com.ocom.common.resp.Result
     * @date 2022/11/9 9:48       
     */
    @PostMapping(WebApiServiceUrl.URL_PermissionremenuMoveUp)
    public Result permissionremenuMoveUp(@RequestBody JSONObject jsonObject){
        return humanClientService.moveUpSaasMenu(jsonObject.getInteger("saasNo"),jsonObject.getInteger("menuId"));
    }

    /**
     *@Description:下移SaaS菜单
     * @author lu 
     * @param jsonObject
     * @return com.ocom.common.resp.Result
     * @date 2022/11/9 9:48       
     */
    @PostMapping(WebApiServiceUrl.URL_PermissionmenuMoveDown)
    public Result permissionmenuMoveDown(@RequestBody JSONObject jsonObject){
        return humanClientService.moveDownSaasMenu(jsonObject.getInteger("saasNo"),jsonObject.getInteger("menuId"));
    }

    /**
     *@Description:添加SaaS菜单
     * @author lu 
     * @param jsonObject
     * @return com.ocom.common.resp.Result
     * @date 2022/11/9 14:57       
     */
    @PostMapping(WebApiServiceUrl.URL_PermissionaddSaasMenu)
    public Result permissionaddSaasMenu(@RequestBody JSONObject jsonObject){
        return humanClientService.addSaasMenu(jsonObject);
    }

    /**
     *@Description:修改SaaS菜单（Permission/modifySaasMenu）
     * @author lu 
     * @param jsonObject
     * @return com.ocom.common.resp.Result
     * @date 2022/11/9 14:58       
     */
    @PostMapping(WebApiServiceUrl.URL_modifySaasMenu)
    public Result permissionmodifySaasMenu(@RequestBody JSONObject jsonObject){
        return humanClientService.modifySaasMenu(jsonObject);
    }

    /**
     *@Description:获取SaaS应用列表
     * @author lu
     * @return com.ocom.common.resp.Result
     * @date 2022/11/9 15:12       
     */
    @PostMapping(WebApiServiceUrl.URL_PermissionsaasList)
    public Result permissionsaasList(){
        return humanClientService.getSaasList();
    }

    @PostMapping(WebApiServiceUrl.URL_MainPagemenuPath)
    public Result mainPagemenuPath(){
        YoCiUser yoCiUser= SecurityUtils.getYoCiUser();
        CompanyListInfoVo companyListInfoVo = new CompanyListInfoVo();
        companyListInfoVo.setComId(yoCiUser.getComId());
        companyListInfoVo.setPage(1);
        companyListInfoVo.setSize(1);
        companyListInfoVo.setOnly(0);
        companyListInfoVo.setComName(null);
        companyListInfoVo.setAgentId(null);

        Result result=companyClientService.GetCompanyListInfo(companyListInfoVo);
        log.info("mainPagemenuPath: 【{}】",result);
        if (result.getCode()==200){
            JSONObject resultJsonObject=JSON.parseObject(JSON.toJSONString(result.getData()),JSONObject.class);
            List<UnitsPageOnShowDto> list = JSONArray.parseArray(JSON.toJSONString(resultJsonObject.get("list")) , UnitsPageOnShowDto.class);
            JSONObject jsonObject=new JSONObject();
            for (UnitsPageOnShowDto unitsPageOnShowDto : list) {
                jsonObject.put("saasNo",unitsPageOnShowDto.getSaasId());
                jsonObject.put("xfVer",unitsPageOnShowDto.getXfStatus());
                jsonObject.put("mjVer",unitsPageOnShowDto.getMjStatus());
                jsonObject.put("saasId",unitsPageOnShowDto.getSaasId());
                jsonObject.put("mjStatus",unitsPageOnShowDto.getMjStatus());
                jsonObject.put("xfStatus",unitsPageOnShowDto.getXfStatus());
                jsonObject.put("role",yoCiUser.getRole());
            }
            jsonObject.put("ifCustom",0);
            if(yoCiUser.getOrgRoleId()>10000l){
                jsonObject.put("ifCustom",1);
                jsonObject.put("role",yoCiUser.getOrgRoleId());
            }
            return humanClientService.getSaasMenuByRole(jsonObject);
        }else {
            return result;
        }
    }
}
